﻿CREATE PROCEDURE [dbo].[Spaces_InsertFromTempSpaces]
	@RangeReviewId INT
AS
	BEGIN TRAN

	DELETE FROM Spaces Where RangeReviewId = @RangeReviewId
	
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RAISERROR('Error borrando espacios actuales.', 16, 1)
		RETURN
	END

	INSERT INTO Spaces (RangeReviewId, StoreId, ArticleId, PlanogramId, Width, Facings)
	Select distinct @RangeReviewId, t.StoreId, t.ArticleId, p.Id PlanogramId, t.Width, t.Facings 
	From TempSpaces t
	Inner Join Planograms p on t.StoreId = p.StoreId and p.RangeReviewId = @RangeReviewId and t.Planogram = p.Name
	where t.ArticleId <> 0
	
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RAISERROR('Error insertando espacios nuevos.', 16, 1)
		RETURN
	END
	
	COMMIT TRAN
	
	